package com.blog.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

public class EmailSendUtils {
    public static final String MY_EMAIL_ACCOUNT = "m18702458404@163.com";
    public static final String MY_EMAIL_PASSWORD = "LHVYNBCBPOGJEOYV";

    // SMTP服务器
    public static final String MEAIL_163_SMTP_HOST = "smtp.163.com";
    public static final String SMTP_163_PORT = "465";// 端口号
    //发送邮件方法
    public static String sendMessage(String email)throws Exception {
        //属性集
        Properties p = new Properties();
        p.setProperty("mail.smtp.host", MEAIL_163_SMTP_HOST);
        p.setProperty("mail.smtp.port", SMTP_163_PORT);
        p.setProperty("mail.smtp.socketFactory.port", SMTP_163_PORT);
        p.setProperty("mail.smtp.auth", "true");//是否需要认证
        p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        p.setProperty("mail.smtp.ssl.enable","true");
        //获取连接
        Session session = Session.getInstance(p, new Authenticator() {
            // 设置认证账户信息
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);
            }
        });
        session.setDebug(true);//设置debug测试
        System.out.println("创建邮件");
        String subject = "欢迎使用TT博客";
        // 生成6位随机验证码
        String verificationCode = String.format("%06d", new Random().nextInt(999999));
        String content = "【TechTales】您的验证码为：" + verificationCode + "，请尽快使用。";
        MimeMessage message = new MimeMessage(session);
        // 发件人
        message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT, "TT", "UTF-8"));
        // 收件人和抄送人
        message.setRecipients(Message.RecipientType.TO, email);
        // 内容
        message.setSubject(subject);
        message.setContent(content, "text/html;charset=UTF-8");
        message.setSentDate(new Date());
        message.saveChanges();//保存设置
        System.out.println("准备发送");
        Transport.send(message);
        System.out.println("发送成功！");
        return verificationCode;
    }
}
